import 'package:demo/constants/app_icon.dart';
import 'package:demo/model/entity/home_entity.dart';
import 'package:demo/model/entity/home_recommend_entity.dart';
import 'package:demo/provider/view_model/home_view_model.dart';
import 'package:demo/provider/widget/base_provider_widget.dart';
import 'package:demo/widget/banner_swiper.dart';
import 'package:demo/widget/pull_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  /// view model
  late final HomeViewModel _viewModel = HomeViewModel();

  int pageNum = 1;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  /// view model创建
  void _onModelReady(HomeViewModel viewModel) async {
    await viewModel.initData();
  }

  /// 下啦刷新
  Future<ActionStatus> _onDataRefresh() async {
    return await Future.delayed(const Duration(seconds: 2), () async {
      await _viewModel.initData();
      return ActionStatus.Success;
    });
  }

  /// 下啦刷新
  Future<ActionStatus> _onLoadMore() async {
    return await Future.delayed(const Duration(seconds: 2), () async {
      final bool isSuccess = await _viewModel.queryRecommendLayout(30, pageNum + 1);
      if (isSuccess) {
        pageNum++;
      }
      return ActionStatus.Success;
    });
  }

  /// 构建定位区域,搜索区域
  Widget get _buildLocationAndSearch {
    return SliverAppBar(
      pinned: true,
      floating: true,
      elevation: 0,
      primary: true,
      toolbarHeight: 48,
      backgroundColor: Color(0xFF029C45),
      centerTitle: false,
      bottom: PreferredSize(
        child: GestureDetector(
          child: Container(
            height: 32,
            margin: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(16),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Icon(search, color: const Color.fromRGBO(156, 156, 156, 1), size: 16),
                Container(
                  margin: const EdgeInsets.only(left: 4),
                  child: const Text(
                    "酸奶",
                    style: TextStyle(
                      fontSize: 12,
                      color: const Color.fromRGBO(156, 156, 156, 1),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        preferredSize: Size.fromHeight(48),
      ),
      title: SizedBox(
        width: 200,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            const Icon(Icons.location_on, color: Colors.white, size: 22),
            Container(
              margin: const EdgeInsets.only(left: 4),
              child: Text(
                "广州",
                style: const TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.w700),
              ),
            ),
            const Icon(Icons.expand_more, color: Colors.white, size: 24),
          ],
        ),
      ),
      actions: <Widget>[
        IconButton(
          icon: const Icon(Icons.notifications, color: Colors.white, size: 24),
          onPressed: () {},
        )
      ],
    );
  }

  /// 构建轮播图刷新器
  Widget get _buildSwiperSelector {
    return Selector<HomeViewModel, List<BannerPicture>>(
      selector: (BuildContext context, HomeViewModel model) => model.homeEntity.banner ?? [],
      child: const SizedBox(width: 0, height: 0),
      builder: _buildSwiperItem,
    );
  }

  /// 构建轮播item
  Widget _buildSwiperItem(BuildContext context, List<BannerPicture> banner, Widget? child) {
    if (banner.length <= 0) return child!;
    return AspectRatio(
      aspectRatio: 700 / 279,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 12),
        decoration: BoxDecoration(color: const Color(0xFF029C45)),
        child: BannerSwiper(
          itemBuilder: (BuildContext context, int index) {
            return DecoratedBox(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(6),
                image: DecorationImage(image: NetworkImage(banner[index].imgUrl ?? ""), fit: BoxFit.fill),
              ),
            );
          },
          bannerLength: banner.length,
        ),
      ),
    );
  }

  /// 构建导航刷新器
  Widget get _buildNavigationSelector {
    final double navWidth = MediaQuery.of(context).size.width / 6;
    return Selector<HomeViewModel, List<Category>>(
      selector: (BuildContext context, HomeViewModel model) {
        return model.homeEntity.category ?? [];
      },
      child: const SizedBox(width: 0, height: 0),
      builder: (BuildContext _, List<Category> data, Widget? child) => _buildNavigationItem(data, child, navWidth),
    );
  }

  /// 构建导航的item
  Widget _buildNavigationItem(List<Category> data, Widget? child, double navWidth) {
    if (data.length <= 0) return child!;

    bool hasFirstRow = true, hasSecondRow = false;

    /// 动态计算2个的高度
    double height = 84;
    const double defaultHeight = 84;

    /// 拆分数组
    List<Category> firstRow = [], secondRow = [];

    if (data.length > 7) {
      hasSecondRow = true;
      height += defaultHeight;
      firstRow = data.sublist(0, 6);
      secondRow = data.sublist(7, data.length);
    } else {
      firstRow = data;
    }

    /// 定义子项布局
    final Widget Function(Category category) itemLayout = (Category element) {
      return SizedBox(
        width: navWidth,
        height: defaultHeight,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Image.network(element.imgUrl!, width: 44),
            Container(
              margin: const EdgeInsets.only(top: 6),
              child: Text(
                element.name!,
                style: const TextStyle(fontSize: 12, color: const Color.fromRGBO(51, 51, 51, 1)),
              ),
            )
          ],
        ),
      );
    };

    return Container(
      height: height,
      margin: const EdgeInsets.only(left: 18, right: 18, top: 12),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(6)),
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (hasFirstRow)
              SizedBox(
                height: defaultHeight,
                child: Row(
                  children: firstRow.map<Widget>(itemLayout).toList(growable: false),
                ),
              ),
            if (hasSecondRow)
              SizedBox(
                height: defaultHeight,
                child: Row(
                  children: secondRow.map<Widget>(itemLayout).toList(growable: false),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 构建宫格推荐的selector
  Widget get _buildRecommendSelector {
    return Selector<HomeViewModel, List<LinkData>>(
      selector: (BuildContext context, HomeViewModel model) => model.recommendEntity,
      child: const SizedBox(width: 0, height: 0),
      builder: _buildRecommendGridItem,
    );
  }

  /// 构建对应的推荐试图子项目
  Widget _buildRecommendGridItem(BuildContext context, List<LinkData> value, Widget? child) {
    return SliverPadding(
      padding: const EdgeInsets.only(left: 18, right: 18, top: 12, bottom: 12),
      sliver: SliverGrid(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 12.0,
          crossAxisSpacing: 12.0,
          crossAxisCount: 2,
          mainAxisExtent: 216,
        ),
        delegate: SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            return AspectRatio(
              aspectRatio: value[index].width! / value[index].height!,
              child: Container(
                color: Colors.white,
                child: Image.network(value[index].thumbnailUrl ?? "", fit: BoxFit.cover),
              ),
            );
          },
          childCount: value.length,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return BaseProviderWidget<HomeViewModel>(
      viewModel: _viewModel,
      showNoIdleHeader: true,
      onModelReady: _onModelReady,
      child: Scaffold(
        backgroundColor: Colors.grey[100],
        body: PullRefresh(
          enablePullRefresh: true,
          enableLoadMore: true,
          onRefresh: _onDataRefresh,
          onLoading: _onLoadMore,
          initialRefresh: true,
          child: CustomScrollView(
            slivers: [
              _buildLocationAndSearch,
              SliverToBoxAdapter(child: _buildSwiperSelector),
              SliverToBoxAdapter(child: _buildNavigationSelector),
              _buildRecommendSelector,
            ],
          ),
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
